package com.daykw.douyin.task;

import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.nutz.dao.Chain;
import org.nutz.dao.Cnd;
import org.nutz.dao.entity.Record;
import org.nutz.dao.impl.NutDao;

import com.daykw.douyin.config.NutzDaoConfig;
import com.daykw.douyin.http.HttpBase;
import com.daykw.douyin.model.VideoAuth;
import com.daykw.douyin.model.VideoInfo;
import com.daykw.douyin.model.VideoSearch;
import com.daykw.douyin.model.VideoTask;
import com.daykw.douyin.utils.SpringContextHolder;

public class VideoSearchThread extends Thread {

	private static Logger logger = Logger.getLogger(VideoSearchThread.class);
	private NutDao dao = SpringContextHolder.getBean(NutzDaoConfig.class);

	@Override
	public void run() {

		List<VideoSearch> list = dao.query(VideoSearch.class, Cnd.where("status", "=", 0).limit(1, 2));

		HttpBase http = new HttpBase();
		Map<String, String> headers = new HashMap<String, String>();
		Record c = dao.fetch("t_cookie", Cnd.where("name", "=", "13235801201"));
		if (c == null) {

			logger.info("cookie:13235801201没了...");
			return;
		}
		String cookie = c.getString("cookie");
		headers.put("Cookie", cookie);

		for (VideoSearch v : list) {

			int page = 1;
			boolean b = true;
			page = v.getPage();
			do {
				try {
					String surl = v.getUrl() + "&page=" + page + "&tag=" + URLEncoder.encode(v.getTag(), "utf-8");
					if (v.getTag().equals("全部")) {
						surl = v.getUrl() + "&page=" + page + "&tag=";
					}

					String html = http.get(surl, headers);

					if (html.indexOf("立即升级会员版本") > 0) {
						b = false;
					} else {

						String dataid = null;
						String awemeid = null;
						String url = null;
						String times = null;
						String auth_url = null;
						if (page > 1) {

							html = "<table>" + html + "</table>";
							Document doc = Jsoup.parse(html);
							Elements awemelist = doc.select("tbody.js-awemelist tr");

							for (Element tr : awemelist) {
								dataid = tr.attr("data-id");
								awemeid = tr.attr("data-awemeid");
								Elements tds = tr.select("td");

								url = "https://dy.feigua.cn/Aweme/Detail?id=" + dataid + "&awemeId=" + awemeid
										+ "&active=detail";

								Element td1 = tds.get(1);
								Element td2 = tds.get(2);
								String img = td1.select("div.item-media img").attr("src");
								times = td1.select("div.item-times").text();
								String href = td2.select("div.item-title a").attr("href");
								href = href.replace("#", "");
								auth_url = "https://dsp.feigua.cn" + href;
								this.saveData(dataid, awemeid, url, times, auth_url, img);

							}

						} else {
							Document doc = Jsoup.parse(html);
							Elements awemelist = doc.select("tbody.js-awemelist tr");

							for (Element tr : awemelist) {
								dataid = tr.attr("data-id");
								awemeid = tr.attr("data-awemeid");
								Elements tds = tr.select("td");

								url = "https://dy.feigua.cn/Aweme/Detail?id=" + dataid + "&awemeId=" + awemeid
										+ "&active=detail";

								Element td1 = tds.get(1);
								Element td2 = tds.get(2);

								times = td1.select("div.item-times").text();
								String img = td1.select("div.item-media img").attr("src");

								String href = td2.select("div.item-title a").attr("href");
								href = href.replace("#", "");
								auth_url = "https://dsp.feigua.cn" + href;
								this.saveData(dataid, awemeid, url, times, auth_url, img);

							}

						}

						page++;
						dao.update(VideoSearch.class, Chain.make("page", page).add("update_time", new Date()),
								Cnd.where("id", "=", v.getId()));
						logger.info("#########列表翻页第" + page + "页" + v.getTag());
						if (page > 25) {
							b = false;
						}
						Thread.sleep(5000);
					}
				} catch (Exception e) {

					logger.error("", e);
				}
			} while (b);
			dao.update(VideoSearch.class, Chain.make("status", 2), Cnd.where("id", "=", v.getId()));
			// System.out.println(ret);

		}

	}

	private void saveData(String dataid, String awemeid, String url, String times, String auth_url, String img) {
		SimpleDateFormat fmt = new SimpleDateFormat("yyyyMMdd");
		VideoTask task = dao.fetch(VideoTask.class, Cnd.where("kw_id", "=", awemeid));

		if (task == null) {
			task = new VideoTask();

			task.setInfo_url(url);
			task.setDataid(dataid);
			task.setKw_id(awemeid);
			// video.setKw_tags(tag);
			// video.setText_content(title);

			times = times.replace("视频时长：", "");
			String[] ts = times.split(" ");
			String min = ts[0];
			Long sec = null;
			if (StringUtils.isNotEmpty(min)) {

				if (min.indexOf("秒") >= 0 && min.indexOf("分") >= 0) {
					Long m = Long.parseLong(min.split("分")[0]);
					String str = min.split("分")[1];
					str = str.split("秒")[0];
					Long s = Long.parseLong(str);
					sec = m * 60000 + s * 1000;

				} else if (min.indexOf("分") >= 0) {
					Long m = Long.parseLong(min.split("分")[0]);
					sec = m * 60000;

				} else if (min.indexOf("秒") >= 0) {
					Long m = Long.parseLong(min.split("秒")[0]);
					sec = m * 1000;

				}
			}

			task.setTimes(sec + "");

			task.setAuth_url(auth_url);

			task.setInfo_status(0);
			task.setUid_status(0);
			task.setCmt_status(0);
			task.setEc_status(5);
			task.setCreate_time(new Date());

			task.setCdate(Integer.parseInt(fmt.format(new Date())));
			try {
				dao.fastInsert(task);
			} catch (Exception e) {
				logger.error("", e);
			}

			VideoAuth auth = new VideoAuth();
			auth.setDataid(dataid);
			auth.setAuth_url(auth_url);
			auth.setStatus(0);
			auth.setOriginal_id(awemeid);
			auth.setVideo_status(0);
			auth.setCreate_time(new Date());
			auth.setCdate(Integer.parseInt(fmt.format(new Date())));
			try {
				dao.fastInsert(auth);
			} catch (Exception e) {
				// logger.error("", e);
				logger.error("dataid重复:" + dataid);
			}

			VideoInfo video = new VideoInfo();

			if (ts.length > 1) {
				video.setHas_product(1);
				String prd = ts[1];
				if (prd.split("：").length > 1) {
					String pname = prd.split("：")[1];
					video.setKw_product_name(pname);
				}

			} else {
				video.setHas_product(0);
			}
			video.setKw_head_image(img);
			video.setDataid(dataid);
			video.setKw_id(awemeid);
			video.setKw_video_duration(ts[0]);
			video.setCreate_time(new Date());
			video.setCdate(Integer.parseInt(fmt.format(new Date())));
			try {
				dao.fastInsert(video);
			} catch (Exception e) {
				logger.error("", e);
			}

		}
	}
	
	public static void main(String[] args) {
		String min = "45秒";
		Long sec = null;
		if (StringUtils.isNotEmpty(min)) {

			if (min.indexOf("秒") >= 0 && min.indexOf("分") >= 0) {
				Long m = Long.parseLong(min.split("分")[0]);
				String str = min.split("分")[1];
				str = str.split("秒")[0];
				Long s = Long.parseLong(str);
				sec = m * 60000 + s * 1000;

			} else if (min.indexOf("分") >= 0) {
				Long m = Long.parseLong(min.split("分")[0]);
				sec = m * 60000;

			} else if (min.indexOf("秒") >= 0) {
				Long m = Long.parseLong(min.split("秒")[0]);
				sec = m * 1000;

			}
		}
		
		System.out.println(sec);

	}
}
